<template>
  <!-- 退款详情 -->
  <div class="refund-detail">
    <Return />

    <!-- 页面标题 -->
    <div class="page-header" :style="{ paddingTop: headerPaddingTop + 'px' }">
      <div class="page-title">退款详情</div>
    </div>

    <scroll-view class="refund-detail-content" scroll-y="true" :style="{ height: contentHeight + 'px' }">
      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <div class="loading">加载中...</div>
      </div>

      <template v-else-if="refundInfo">
        <!-- 订单信息 -->
        <div class="info-card">
          <div class="card-title">订单信息</div>
          <div class="info-list">
            <div class="info-item">
              <div class="info-label">订单号</div>
              <div class="info-value">{{ refundInfo.orderNo }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">申请时间</div>
              <div class="info-value">{{ refundInfo.createTime }}</div>
            </div>
          </div>
        </div>

        <!-- 用户信息 -->
        <div class="info-card">
          <div class="card-title">用户信息</div>
          <div class="info-list">
            <div class="info-item">
              <div class="info-label">联系人</div>
              <div class="info-value">{{ refundInfo.contactName || '未提供' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">联系电话</div>
              <div class="info-value phone-value" @click="makePhoneCall(refundInfo.contactPhone)" v-if="refundInfo.contactPhone">
                <span class="phone-number">{{ refundInfo.contactPhone }}</span>
                <span class="phone-icon">📞</span>
              </div>
              <div class="info-value" v-else>未提供</div>
            </div>
          </div>
        </div>

        <!-- 在用户信息卡片后面添加商品信息 -->
        <!-- 商品信息 -->
        <div class="info-card" v-if="refundInfo.orderGoodsList && refundInfo.orderGoodsList.length > 0">
          <div class="card-title">商品信息</div>
          <div class="goods-list">
            <div v-for="(goods, index) in refundInfo.orderGoodsList" :key="index" class="goods-item">
              <image :src="goods.goodsImage || '../static/imgs/caipinmoren.png'" mode="aspectFill" class="goods-image"></image>
              <div class="goods-info">
                <div class="goods-name">{{ goods.goodsName }}</div>
                <div class="goods-priceStr">
                  <span class="priceStr-amount">¥{{ goods.priceStr }}</span>
                  <span class="priceStr-quantity">× {{ goods.goodsNum }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 退款信息 -->
        <div class="info-card">
          <div class="card-title">退款信息</div>
          <div class="info-list">
            <div class="info-item">
              <div class="info-label">退款金额</div>
              <div class="info-value refund-amount">¥{{ refundInfo.needPayAmountStr }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">退款原因</div>
              <div class="info-value">{{ refundInfo.refundCause }}</div>
            </div>
            <div class="info-item" v-if="refundInfo.refundDesc">
              <div class="info-label">退款说明</div>
              <div class="info-value">{{ refundInfo.refundDesc }}</div>
            </div>
          </div>
        </div>

        <!-- 退款凭证 -->
        <div class="info-card" v-if="refundInfo.refundImg">
          <div class="card-title">退款凭证</div>
          <div class="images-list">
            <image v-for="(img, imgIndex) in getRefundImages(refundInfo.refundImg)" :key="imgIndex"
              :src="img" mode="aspectFill" @click="previewImage(img, getRefundImages(refundInfo.refundImg))"
              class="refund-image"/>
          </div>
        </div>

        <!-- 审核记录 -->
        <div class="info-card" v-if="refundInfo.approvalTime">
          <div class="card-title">审核记录</div>
          <div class="approval-timeline">
            <div class="timeline-item">
              <div class="timeline-dot" :class="getStatusClass(refundInfo.shopApprovalStatus)"></div>
              <div class="timeline-content">
                <div class="timeline-title">{{ getStatusText(refundInfo.shopApprovalStatus) }}</div>
                <div class="timeline-time">{{ refundInfo.approvalTime }}</div>
                <div class="timeline-desc" v-if="refundInfo.approvalRemark">
                  备注：{{ refundInfo.approvalRemark }}
                </div>
              </div>
            </div>
            <div class="timeline-item">
              <div class="timeline-dot status-pending"></div>
              <div class="timeline-content">
                <div class="timeline-title">提交申请</div>
                <div class="timeline-time">{{ refundInfo.createTime }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions" v-if="refundInfo && refundInfo.shopApprovalStatus == '0'">
      <div class="action-buttons">
        <div class="action-btn secondary" @click="handleRefund('2')">
          拒绝退款
        </div>
        <div class="action-btn primary" @click="handleRefund('1')">
          同意退款
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Return from '@/components/Return.vue'

const headerPaddingTop = ref(0)
const contentHeight = ref(600)
const loading = ref(false)
const refundInfo = ref(null)

// 状态文字映射
const statusTextMap = {
  '0': '待处理',
  '1': '已同意',
  '2': '已拒绝'
}

// 状态描述映射
const statusDescMap = {
  '0': '商家正在审核您的退款申请',
  '1': '退款申请已通过，请等待退款到账',
  '2': '退款申请已被拒绝'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || '未知状态'
}

// 获取状态描述
const getStatusDesc = (status) => {
  return statusDescMap[status] || ''
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    '0': 'status-pending',
    '1': 'status-approved',
    '2': 'status-rejected'
  }
  return classMap[status] || ''
}

// 处理退款图片
const getRefundImages = (refundImg) => {
  if (!refundImg) return []

  if (typeof refundImg === 'string') {
    return refundImg.split(',').filter(img => img.trim())
  }

  if (Array.isArray(refundImg)) {
    return refundImg
  }

  return []
}

// 图片预览
const previewImage = (current, urls) => {
  uni.previewImage({
    current,
    urls
  })
}

// 拨打电话
const makePhoneCall = (phoneNumber) => {
  if (!phoneNumber) {
    uni.showToast({
      title: '联系电话未提供',
      icon: 'none'
    })
    return
  }
  uni.makePhoneCall({
    phoneNumber: phoneNumber,
    success: function () {
      uni.showToast({
        title: '拨打电话成功',
        icon: 'success'
      })
    },
    fail: function (e) {
      uni.showToast({
        title: '拨打电话失败: ' + e.message,
        icon: 'none'
      })
    }
  })
}

// 计算内容区高度
const calcContentHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  headerPaddingTop.value = menuButtonInfo.bottom + 20
  // #endif
  contentHeight.value = systemInfo.windowHeight - headerPaddingTop.value - 60 - 100
}

// 获取完整的退款信息（合并两个接口的数据）
const fetchCompleteRefundInfo = async (refundId, orderId) => {
  loading.value = true

  try {
    // 并行请求两个接口
    const [refundResponse, orderResponse] = await Promise.all([
      Fetch(`shopping/refundRequest/${refundId}`, {
        method: 'GET'
      }),
      Fetch(`shopping/orderInfo/getOrderInfoAndGoods/${orderId}`, {
        method: 'GET'
      })
    ])

    console.log('退款详情接口返回:', refundResponse)
    console.log('订单信息接口返回:', orderResponse)

    // 检查两个接口是否都成功
    if (refundResponse.status === 200 && refundResponse.data.code === 200 &&
        orderResponse.status === 200 && orderResponse.data.code === 200) {

      const refundData = refundResponse.data.data
      const orderData = orderResponse.data.data

      // 合并数据
      refundInfo.value = {
        // 退款相关信息
        ...refundData,
        ...orderData,
        // 订单相关信息

      }

      console.log('合并后的退款信息:', refundInfo.value)

    } else {
      // 处理接口错误
      const errorMsg = refundResponse.data?.msg || orderResponse.data?.msg || '获取详情失败'
      uni.showToast({
        title: errorMsg,
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取退款详情失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 处理退款审核
const handleRefund = async (action) => {
  const isApprove = action === '1'

  if (!isApprove) {
    uni.showModal({
      title: '拒绝原因',
      editable: true,
      placeholderText: '请输入拒绝原因（可选）',
      success: async (res) => {
        if (res.confirm) {
          await submitRefundDecision(action, res.content)
        }
      }
    })
  } else {
    uni.showModal({
      title: '确认提示',
      content: '确认同意此退款申请？',
      success: async (res) => {
        if (res.confirm) {
          await submitRefundDecision(action, '')
        }
      }
    })
  }
}

// 提交审核决定
const submitRefundDecision = async (action, remark = '') => {
  const isApprove = action === '1'

  try {
    const result = await Fetch('shopping/refundRequest/edit', {
      method: 'PUT',
      data: {
        refundRequestId: refundInfo.value.refundRequestId || refundInfo.value.id,
        shopApprovalStatus: isApprove ? '1' : '2',
        approvalRemark: remark
      }
    })

    if (result.data.code == 200) {
      uni.showToast({
        title: isApprove ? '已同意退款' : '已拒绝退款',
        icon: 'success'
      })

      // 刷新详情 - 重新获取合并数据
      setTimeout(() => {
        if (refundInfo.value.refundRequestId && refundInfo.value.orderId) {
          fetchCompleteRefundInfo(refundInfo.value.refundRequestId, refundInfo.value.orderId)
        }
      }, 1000)
    } else {
      uni.showToast({
        title: result.data.msg || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

onLoad(async (options) => {
  console.log('页面参数:', options)

  if (options.refundId && options.orderId) {
    // 获取合并后的完整信息
    await fetchCompleteRefundInfo(options.refundId, options.orderId)
  } else {
    uni.showToast({
      title: '缺少必要参数',
      icon: 'none'
    })
  }
})

onMounted(() => {
  calcContentHeight()
})
</script>

<style lang="scss" scoped>
.refund-detail {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;

  .page-header {
    background: #FFFFFF;
    padding: 0 24rpx 20rpx;
    margin-bottom: 20rpx;

    .page-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #191919;
      text-align: center;
    }
  }

  .refund-detail-content {
    flex: 1;
    overflow: auto;
    padding: 0 20rpx;
    box-sizing: border-box;

    .loading-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 400rpx;

      .loading {
        color: #999;
        font-size: 28rpx;
      }
    }

    .status-card {
      background: #FFFFFF;
      border-radius: 20rpx;
      padding: 40rpx 24rpx;
      margin-bottom: 20rpx;
      text-align: center;

      .status-info {
        display: flex;
        align-items: center;
        justify-content: center;

        .status-icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 24rpx;
          font-size: 40rpx;

          &.status-pending {
            background: #FFF7E6;
            color: #FA8C16;
          }

          &.status-approved {
            background: #F6FFED;
            color: #52C41A;
          }

          &.status-rejected {
            background: #FFF2F0;
            color: #FF4D4F;
          }
        }

        .status-text {
          text-align: left;

          .status-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #191919;
            margin-bottom: 8rpx;
          }

          .status-desc {
            font-size: 26rpx;
            color: #666;
          }
        }
      }
    }

    .info-card {
      background: #FFFFFF;
      border-radius: 20rpx;
      padding: 24rpx;
      margin-bottom: 20rpx;

      .card-title {
        font-size: 30rpx;
        font-weight: bold;
        color: #191919;
        margin-bottom: 20rpx;
        padding-bottom: 16rpx;
        border-bottom: 1px solid #f5f5f5;
      }

      .info-list {
        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 16rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .info-label {
            color: #666;
            font-size: 26rpx;
            min-width: 120rpx;
          }

          .info-value {
            color: #191919;
            font-size: 26rpx;
            text-align: right;
            flex: 1;
            word-break: break-all;

            &.refund-amount {
              color: #FF4D4F;
              font-weight: bold;
              font-size: 28rpx;
            }

            &.phone-value {
              color: #007BFF;
              font-size: 26rpx;
              cursor: pointer;
              display: flex;
              align-items: center;
              justify-content: flex-end;

              .phone-number {
                margin-right: 10rpx;
              }

              .phone-icon {
                font-size: 24rpx;
              }
            }
          }
        }
      }

      .images-list {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;

        .refund-image {
          width: 180rpx;
          height: 180rpx;
          border-radius: 8rpx;
        }
      }

      .approval-timeline {
        .timeline-item {
          display: flex;
          align-items: flex-start;
          margin-bottom: 24rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .timeline-dot {
            width: 20rpx;
            height: 20rpx;
            border-radius: 50%;
            margin-right: 20rpx;
            margin-top: 4rpx;
            flex-shrink: 0;

            &.status-pending {
              background: #FA8C16;
            }

            &.status-approved {
              background: #52C41A;
            }

            &.status-rejected {
              background: #FF4D4F;
            }
          }

          .timeline-content {
            flex: 1;

            .timeline-title {
              font-size: 28rpx;
              color: #191919;
              font-weight: 500;
              margin-bottom: 8rpx;
            }

            .timeline-time {
              font-size: 24rpx;
              color: #999;
              margin-bottom: 8rpx;
            }

            .timeline-desc {
              font-size: 24rpx;
              color: #666;
              background: #F8F8F8;
              padding: 12rpx;
              border-radius: 8rpx;
            }
          }
        }
      }

      .goods-list {
        .goods-item {
          display: flex;
          align-items: flex-start;
          padding: 20rpx;
          margin-bottom: 16rpx;
          background: #F8F8F8;
          border-radius: 16rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .goods-image {
            width: 140rpx;
            height: 140rpx;
            border-radius: 12rpx;
            margin-right: 20rpx;
            flex-shrink: 0;
          }

          .goods-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            min-height: 140rpx;

            .goods-name {
              font-size: 28rpx;
              color: #191919;
              font-weight: bold;
              margin-bottom: 12rpx;
              line-height: 1.4;
              // 限制显示行数，避免文字过长
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

            .goods-spec {
              font-size: 24rpx;
              color: #999;
              margin-bottom: 12rpx;
              background: #FFFFFF;
              padding: 8rpx 12rpx;
              border-radius: 20rpx;
              align-self: flex-start;
              max-width: 80%;
            }

            .goods-priceStr {
              font-size: 28rpx;
              color: #FF4D4F;
              font-weight: bold;
              margin-top: auto;
              display: flex;
              justify-content: space-between;
              align-items: center;

              .priceStr-amount {
                font-size: 30rpx;
              }

              .priceStr-quantity {
                font-size: 24rpx;
                color: #666;
                font-weight: normal;
              }
            }
          }
        }
      }
    }
  }

  .bottom-actions {
    background: #FFFFFF;
    padding: 20rpx 24rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    border-top: 1px solid #f5f5f5;

    .action-buttons {
      display: flex;
      gap: 20rpx;

      .action-btn {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border-radius: 40rpx;
        font-size: 28rpx;
        font-weight: bold;

        &.primary {
          background-color: #F9DC40;
          color: #191919;
        }

        &.secondary {
          background-color: #E0E0E0;
          color: #191919;
        }
      }
    }
  }
}
</style>
